<template>
  <div class="user-analytics">
    <el-card class="page-header">
      <template #header>
        <div class="header-title">
          <h2>用户数据分析</h2>
          <div class="filter-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button @click="exportData">导出报表</el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalUsers }}</div>
              <div class="data-label">总用户数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value up">+{{ stats.newUsers }}</span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.activeUsers }}</div>
              <div class="data-label">活跃用户</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.activeUsersTrend > 0 ? 'up' : 'down'">
                {{ stats.activeUsersTrend > 0 ? '+' : '' }}{{ stats.activeUsersTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.avgActiveTime }}</div>
              <div class="data-label">平均活跃时长(分钟)</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.avgActiveTimeTrend > 0 ? 'up' : 'down'">
                {{ stats.avgActiveTimeTrend > 0 ? '+' : '' }}{{ stats.avgActiveTimeTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.retention }}%</div>
              <div class="data-label">用户留存率</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.retentionTrend > 0 ? 'up' : 'down'">
                {{ stats.retentionTrend > 0 ? '+' : '' }}{{ stats.retentionTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表展示 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户增长趋势</span>
                <el-radio-group v-model="userGrowthType" size="small">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="userGrowthChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户活跃度分布</span>
              </div>
            </template>
            <div ref="userActivityChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户年龄分布</span>
              </div>
            </template>
            <div ref="ageDistributionChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户地域分布</span>
                <el-select v-model="regionType" size="small" style="width: 100px">
                  <el-option label="省份" value="province" />
                  <el-option label="城市" value="city" />
                </el-select>
              </div>
            </template>
            <div ref="regionDistributionChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
// import { initChart, getLineChartOption, getBarChartOption, getPieChartOption } from '@/utils/echarts'
// import { get } from '@/utils/request'

// 图表实例
const userGrowthChart = ref(null)
const userActivityChart = ref(null)
const ageDistributionChart = ref(null)
const regionDistributionChart = ref(null)

// 图表DOM元素
const userGrowthChartEl = ref(null)
const userActivityChartEl = ref(null)
const ageDistributionChartEl = ref(null)
const regionDistributionChartEl = ref(null)

// 过滤条件
const dateRange = ref([])
const userGrowthType = ref('daily')
const regionType = ref('province')

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 数据统计
const stats = reactive({
  totalUsers: 12580,
  newUsers: 328,
  activeUsers: 4213,
  activeUsersTrend: 12.5,
  avgActiveTime: 32,
  avgActiveTimeTrend: -2.1,
  retention: 67.8,
  retentionTrend: 5.3
})

// 模拟数据 - 用户增长
const userGrowthData = {
  daily: {
    xData: ['5/1', '5/2', '5/3', '5/4', '5/5', '5/6', '5/7'],
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: [45, 52, 38, 41, 56, 67, 69]
      },
      {
        name: '累计用户',
        type: 'line',
        data: [12200, 12252, 12290, 12331, 12387, 12454, 12523]
      }
    ]
  },
  weekly: {
    xData: ['第1周', '第2周', '第3周', '第4周'],
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: [283, 314, 358, 401]
      },
      {
        name: '累计用户',
        type: 'line',
        data: [11800, 12114, 12472, 12873]
      }
    ]
  },
  monthly: {
    xData: ['1月', '2月', '3月', '4月', '5月'],
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: [950, 875, 1020, 1135, 1356]
      },
      {
        name: '累计用户',
        type: 'line',
        data: [8500, 9375, 10395, 11530, 12886]
      }
    ]
  }
}

// 用户活跃度数据
const userActivityData = {
  legend: ['高活跃', '中活跃', '低活跃', '沉睡用户'],
  series: {
    name: '用户活跃度',
    data: [
      { value: 28, name: '高活跃' },
      { value: 35, name: '中活跃' },
      { value: 25, name: '低活跃' },
      { value: 12, name: '沉睡用户' }
    ]
  }
}

// 年龄分布数据
const ageDistributionData = {
  xData: ['18岁以下', '18-24岁', '25-30岁', '31-40岁', '41-50岁', '50岁以上'],
  series: [
    {
      name: '用户数量',
      type: 'bar',
      data: [1220, 3520, 4580, 2150, 860, 250]
    }
  ]
}

// 地域分布数据
const regionDistributionData = {
  province: {
    xData: ['广东', '北京', '上海', '浙江', '江苏', '湖北', '四川', '其他'],
    series: [
      {
        name: '用户数量',
        type: 'bar',
        data: [2850, 1980, 1750, 1420, 1350, 980, 850, 1400]
      }
    ]
  },
  city: {
    xData: ['广州', '北京', '上海', '深圳', '杭州', '武汉', '成都', '其他'],
    series: [
      {
        name: '用户数量',
        type: 'bar',
        data: [1850, 1980, 1750, 1000, 920, 980, 850, 3250]
      }
    ]
  }
}

// 初始化图表
const initCharts = () => {
  // 由于缺少echarts依赖，这里暂时不初始化图表
  // 实际代码应该类似以下：
  
  // userGrowthChartEl.value = initChart(userGrowthChart.value, getLineChartOption({
  //   title: '用户增长趋势',
  //   xData: userGrowthData[userGrowthType.value].xData,
  //   series: userGrowthData[userGrowthType.value].series,
  //   legend: ['新增用户', '累计用户']
  // }))
  
  // userActivityChartEl.value = initChart(userActivityChart.value, getPieChartOption({
  //   title: '用户活跃度分布',
  //   series: userActivityData.series
  // }))
  
  // ageDistributionChartEl.value = initChart(ageDistributionChart.value, getBarChartOption({
  //   title: '用户年龄分布',
  //   xData: ageDistributionData.xData,
  //   series: ageDistributionData.series
  // }))
  
  // regionDistributionChartEl.value = initChart(regionDistributionChart.value, getBarChartOption({
  //   title: '用户地域分布',
  //   xData: regionDistributionData[regionType.value].xData,
  //   series: regionDistributionData[regionType.value].series
  // }))
}

// 更新图表
const updateCharts = () => {
  // 更新用户增长趋势图表
  if (userGrowthChartEl.value) {
    userGrowthChartEl.value.setOption({
      xAxis: { data: userGrowthData[userGrowthType.value].xData },
      series: userGrowthData[userGrowthType.value].series
    })
  }

  // 更新用户活跃度图表
  if (userActivityChartEl.value) {
    userActivityChartEl.value.setOption({
      xAxis: { data: userActivityData.xData },
      series: userActivityData.series
    })
  }

  // 更新年龄分布图表
  if (ageDistributionChartEl.value) {
    ageDistributionChartEl.value.setOption({
      series: [ageDistributionData.series]
    })
  }

  // 更新地区分布图表
  if (regionDistributionChartEl.value) {
    regionDistributionChartEl.value.setOption({
      series: [regionDistributionData.series]
    })
  }
}

// 处理日期变化
const handleDateChange = () => {
  updateCharts()
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  updateCharts()
}

// 导出报表
const exportData = () => {
  ElMessage.success('报表导出中，请稍后查看下载文件')
}

// 监听过滤条件变化
watch(userGrowthType, () => {
  updateCharts()
})

watch(regionType, () => {
  updateCharts()
})

// 监听窗口大小变化，重新调整图表大小
const resizeHandler = () => {
  userGrowthChartEl.value?.resize()
  userActivityChartEl.value?.resize()
  ageDistributionChartEl.value?.resize()
  regionDistributionChartEl.value?.resize()
}

// 生命周期钩子
onMounted(() => {
  // 设置默认日期范围为最近一个月
  dateRange.value = dateShortcuts[1].value()
  
  // 初始化图表
  setTimeout(initCharts, 100)
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped>
.user-analytics {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
}

.filter-actions {
  display: flex;
  gap: 15px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.data-card-content {
  text-align: center;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.data-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.data-trend {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.trend-value {
  font-weight: 500;
}

.trend-value.up {
  color: #67c23a;
}

.trend-value.down {
  color: #f56c6c;
}

.trend-label {
  color: #909399;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
}

@media (max-width: 768px) {
  .header-title {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-top: 15px;
    flex-wrap: wrap;
  }
  
  .chart {
    height: 250px;
  }
}
</style> 